package com.iha.pongzor.gui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.iha.pongzor.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Downloader extends Activity {

	private ProgressBar downloaderBar;
	private TextView downloaderText;
	private Handler progresshandler = new Handler();
	private int progressProcentage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloader);

		downloaderText = (TextView) findViewById(R.id.downloaderTextView);
		downloaderBar = (ProgressBar) findViewById(R.id.downloadProgressBar);
		downloadtester();
	}

	public void downloadtester() {

		new Thread(new Runnable() {
			public void run() {

				try {

					String res = getString(R.string.mp3);
					// create a new file, specifying the path, and the filename
					// which we want to save the file as.
					File SDCardRoot = Environment.getExternalStorageDirectory();
					File dir = new File(SDCardRoot.getAbsolutePath() + getString(R.string.musicFolderDir));
					dir.mkdirs();
					File file = new File(dir, res);

					downloaderText.setText(R.string.mp3);
					URL url = new URL(TextUtils.htmlEncode(getString(R.string.onlineMusicURL) + res));

					// create the new connection
					HttpURLConnection Con = (HttpURLConnection) url.openConnection();
					Con.setRequestMethod("GET");
					Con.setDoOutput(true);
					Con.connect();

					FileOutputStream fileOutput = new FileOutputStream(file);

					BufferedInputStream inputStream = new BufferedInputStream(Con.getInputStream());

					int totalSize = Con.getContentLength();
					int downloadedSize = 0;

					byte[] buffer = new byte[1024];
					int bufferLength = 0;

					while ((bufferLength = inputStream.read(buffer)) > -1) {

						fileOutput.write(buffer, 0, bufferLength);

						downloadedSize += bufferLength;
						progressProcentage = downloadedSize * 100 / totalSize;

						progresshandler.post(new Runnable() {
							public void run() {
								downloaderBar.setProgress(progressProcentage);
								if (progressProcentage == 100) {
									Toast.makeText(getApplicationContext(), getString(R.string.mp3) + " is downloaded :D", Toast.LENGTH_SHORT).show();
									finish();
								}

							}
						});
					}
					fileOutput.close();

				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}).start();
	}
}
